package sysService

import (
	"context"
	"fmt"
	"gitee.com/jokces/kit/enum"
	"gitee.com/jokces/kit/errc"
	"gitee.com/jokces/kit/gen/uid"
	sysModel "gitee.com/jokces/kit/global/admin/model"
	"gitee.com/jokces/kit/global/admin/util"
	"gitee.com/jokces/kit/typ"
)

// UserPageList 用户
func (svc *Service) UserPageList(ctx context.Context, in *sysModel.UserListReq, sess sysModel.AdminUserToken) (typ.ListResp, error) {
	rs := typ.ListResp{}
	query := &sysModel.SysUser{
		LikeUserName: in.UserName,
		Email:        in.Email,
		Phone:        in.Phone,
		Status:       in.Status,
		DepId:        in.DepId,
	}
	if in.DepId <= 0 {
		query.DepId = sess.DepId
	}
	count, users, err := svc.d.UserPageList(ctx, query, in.PageReq)
	if err != nil {
		return rs, err
	}
	rs.Count = count
	rs.List = users
	return rs, nil
}
func (svc *Service) UserAdd(ctx context.Context, req *sysModel.UserAddReq) error {
	u, err := svc.userAddCheck(ctx, req)
	if err != nil {
		return err
	}
	if id, err := uid.GenID(); err != nil {
		return errc.ErrInternalErr.MultiMsg("编号处理错误")
	} else {
		u.Uid = fmt.Sprintf("%v", id)
	}
	u.Pass = util.AdminLoginPass(req.Pass, u.Salt)
	if err := svc.d.GetDao().TxInsert(nil, u); err != nil {
		return errc.WithStack(err)
	}
	return nil
}
func (svc *Service) UserEdit(ctx context.Context, req *sysModel.UserEditReq) error {
	u, err := svc.userEditCheck(ctx, req)
	if err != nil {
		return err
	}
	if err := svc.d.GetDao().TxBeanUpdate(nil, req.Id, u); err != nil {
		return errc.WithStack(err)
	}
	return nil
}
func (svc *Service) UserDisabled(ctx context.Context, req *sysModel.CommonDisabledReq, sess sysModel.AdminUserToken) error {
	if sess.RootRole() && req.Id == sess.Id {
		return errc.ErrParamInvalid.MultiMsg("超级管理员不能停用")
	}
	exist, u, err := svc.d.UserGetOne(ctx, sysModel.SysUser{
		Id: req.Id,
	})
	if err != nil {
		return errc.WithStack(err)
	} else if !exist {
		return errc.ErrParamInvalid.MultiMsg("账户不存在")
	}
	if req.Status > 0 && !sysModel.CheckCommonStatus(req.Status) {
		return errc.ErrParamInvalid.MultiMsg("状态不正确")
	}
	if u.Status == req.Status {
		return nil
	}
	if err := svc.d.GetDao().TxUpdate(nil, req.Id, sysModel.SysUser{
		Status: req.Status,
	}, []string{"`status`"}); err != nil {
		return errc.WithStack(err)
	}

	if req.Status == enum.DISABLED {
		if err := svc.UserLoginLimit(u.Id, sysModel.AdminType); err != nil {
			return err
		}
	}
	return nil
}
func (svc *Service) UserRestPass(ctx context.Context, req *sysModel.UserRestPassReq, sess sysModel.AdminUserToken) error {
	id := req.Id
	if req.Id == 0 {
		if req.OldPass == "" {
			return errc.ErrParamInvalid.MultiMsg("原密码不能为空")
		}
		id = sess.Id
	}
	exist, u, err := svc.d.UserGetOne(ctx, sysModel.SysUser{
		Id: id,
	})
	if err != nil {
		return errc.WithStack(err)
	} else if !exist {
		return errc.ErrParamInvalid.MultiMsg("用户不存在")
	}

	if req.Id == 0 && !u.CheckPass(req.OldPass) {
		return errc.ErrParamInvalid.MultiMsg("原密码不正确")
	}

	if err := svc.d.GetDao().TxUpdate(nil, u.Id, sysModel.SysUser{
		Pass: util.AdminLoginPass(req.Pass, u.Salt),
	}, []string{"pass"}); err != nil {
		return errc.WithStack(err)
	}
	return nil
}
func (svc *Service) UserRestInfo(ctx context.Context, req *sysModel.UserRestInfoReq, sess sysModel.AdminUserToken) error {
	exist, u, err := svc.d.UserGetOne(ctx, sysModel.SysUser{
		Id: sess.Id,
	})
	if err != nil {
		return errc.WithStack(err)
	} else if !exist {
		return errc.ErrParamInvalid.MultiMsg("用户不存在")
	}

	up := &sysModel.SysUser{
		Id:       u.Id,
		NickName: req.Nickname,
	}

	//检查电话号码，邮箱地址
	phone, email := req.Phone, req.Email
	if phone != u.Phone || email != u.Email {
		if ok, err := svc.d.CountMobileOrEmail(req.Phone, req.Email); err != nil {
			return err
		} else if ok {
			return errc.ErrParamInvalid.MultiMsg("邮箱|手机号重复")
		}
	}
	if phone != "" {
		up.Phone = phone
	}
	if email != "" {
		up.Email = email
	}
	if err := svc.d.GetDao().TxBeanUpdate(nil, u.Id, up); err != nil {
		return errc.WithStack(err)
	}
	return nil
}
func (svc *Service) UserInfo(ctx context.Context, sess sysModel.AdminUserToken) (*sysModel.UserInfoResp, error) {
	info := &sysModel.UserInfoResp{}
	exist, user, err := svc.d.AdminSessionGet(ctx, sess.Id)
	if err != nil {
		return info, err
	}
	if !exist {
		return info, errc.ErrParamInvalid.MultiMsg("账户不存在或已被冻结")
	}

	if err := svc.userRole(ctx, sess, info); err != nil {
		return info, err
	}
	info.DepName = user.DepName
	info.UserName = user.UserName
	info.Phone = user.Phone
	info.Email = user.Email
	info.NickName = user.NickName
	return info, nil
}
func (svc *Service) UserMenu(ctx context.Context, sess sysModel.AdminUserToken) ([]*sysModel.UserMenus, error) {
	return svc.userInfoMenu(ctx, sess)
}

func (svc *Service) AdminSession(ctx context.Context, userId int64) (*sysModel.AdminUserToken, error) {
	exist, token, err := svc.d.AdminSessionGet(ctx, userId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return nil, errc.ErrNotFound.MultiMsg("账户未开通")
	}
	return token, nil
}
func (svc *Service) UserPass(ctx context.Context, in *sysModel.AccessTokenReq) (*sysModel.SysUser, error) {
	user, err := svc.UserOne(ctx, sysModel.SysUser{
		UserName: in.UserName,
		Phone:    typ.GlobalMobile(in.Phone),
		Email:    in.Email,
	})
	if err != nil {
		return user, err
	}

	if checkPass := user.CheckPass(in.Password); !checkPass {
		return nil, errc.ErrNotFound.MultiMsg("密码不正确")
	}
	return user, nil
}
func (svc *Service) UserOne(ctx context.Context, in sysModel.SysUser) (*sysModel.SysUser, error) {
	exist, user, err := svc.d.UserGetOne(ctx, in)
	if err != nil {
		return nil, err
	}
	if !exist {
		return nil, errc.ErrNotFound.MultiMsg("用户未注册")
	}
	if user.Status == enum.DISABLED {
		return nil, errc.ErrNotFound.MultiMsg("账户已被停用")
	}
	return user, nil
}
